package com.cloud.logger.zchain.zchainserver.zoo2;

import com.cloud.logger.zchain.core.constants.Constants;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

/**
 * @Author: wcy
 * @Description:
 * @Date: Created in 2017/12/12 14:38
 * @Modified By:
 */
public class AppServer {
    private String groupNode = "sgroup";
    private String subNode = "sub";
    private static final String ZK_PATH = "/example/pathCache";
    /**
     * 连接zookeeper
     * @param address server的地址
     */
    public void connectZookeeper(String address) throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, Integer.MAX_VALUE);
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("115.159.160.97:2181")
                .retryPolicy(retryPolicy)
                .sessionTimeoutMs(6000)
                .connectionTimeoutMs(3000)
                .namespace("zchain-schedule")
                .build();
        client.start();

        Stat stat =client.checkExists().forPath(Constants.ZK_PROJECT_PATH+"/"+address);

        if(stat!=null)
            client.delete().forPath(Constants.ZK_PROJECT_PATH+"/"+address);
        // 在"/sgroup"下创建子节点
        // 子节点的类型设置为EPHEMERAL_SEQUENTIAL, 表明这是一个临时节点, 且在子节点的名称后面加上一串数字后缀
        // 将server的地址数据关联到新创建的子节点上
        String createdPath = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).
                forPath(Constants.ZK_PROJECT_PATH+"/"+address, address.getBytes());
        System.out.println("create: " + createdPath);

    }

    /**
     * server的工作逻辑写在这个方法中
     * 此处不做任何处理, 只让server sleep
     */
    public void handle() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }

    public static void main(String[] args) throws Exception {
        String a = "111.1.1.1.1";

        AppServer as = new AppServer();
        as.connectZookeeper(a);

        as.handle();
    }
}
